package domain;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.ByteBuffer;

public class CheckServerStatusThread extends Thread {
	
	private String receivedIp;
	private MulticastSocket multicastSocket;
	private long currentServerStatusId;
	private DatagramPacket serverIpPacket;

	public CheckServerStatusThread(String address, int port){
		try{
			multicastSocket = new MulticastSocket(port);
			InetAddress ipGroup = InetAddress.getByName(address);
			multicastSocket.joinGroup(ipGroup);
		}catch (IOException e) {
			System.out.println("Error joining multicast group: " + e);
		}
	}
	
	public void run(){
		while(true){
			try{
				byte[] buf = new byte[256];
				serverIpPacket = new DatagramPacket(buf, buf.length);
				multicastSocket.receive(serverIpPacket);
				
				//Get ip from server, so further datagrams can be send from the client
				receivedIp = serverIpPacket.getAddress().getHostAddress();
				ClientDomainController.setServerIp(receivedIp);
				
				ByteBuffer buffer = ByteBuffer.wrap(serverIpPacket.getData());
				currentServerStatusId = buffer.getLong();
				System.out.println("received current ServerStatusId: " + currentServerStatusId);
				if(currentServerStatusId!=ClientDomainController.getCurrentServerStatusId()){
					ClientDomainController.requestServerStatusUpdate();
				}
				
			}catch (IOException e) {
				System.out.println("error in receiving serverStatusId: " + e);
			}
		}
	}

}
